<template>
	<common-page>
    <image src="../../static/device_bg.jpg" mode="widthFix" class="device-img"></image>
		<text class="txt-tip font-30">安装说明：请为设备通电并等待指示灯变为闪烁待接入状态</text>
		<view class="radio-wrap">
			<u-radio-group v-model="isRead" @change="groupChange">
				<u-radio label="已确认上述操作" :name="true" labelColor="#9FA2B4"></u-radio>
			</u-radio-group>
		</view>
		<view class="btn-next">
			<u-button type="primary" :disabled="!isRead" text="继续" color="#417CE9"  @click="bindAddDevice"></u-button>
		</view>
		<u-popup :show="show" mode="bottom" :closeOnClickOverlay="false" bgColor="transparent">
			<view class="page-box-popup">
					<view class="content-wrap">
						<view class="title flex">
							<text>{{ popupContent[popupType].title }}</text>
							<view class="margin-left-10" v-if="[2,6].includes(popupType)">
								<u-icon
									name="checkmark-circle-fill" color="#2DE3C5" size="18"
								></u-icon>
							</view>
							<view class="margin-left-10" v-if="[3,7].includes(popupType)">
								<u-icon
									name="close-circle-fill" color="#F15454" size="18"
								></u-icon>
							</view>
						</view>
						<view class="subTitle" v-if="popupContent[popupType].subTitle">
							{{ popupContent[popupType].subTitle }}
						</view>
						<u--form
							style="width: 560rpx;"
							labelPosition="top"
							labelWidth="500rpx"
							:model="formData"
							:rules="{}"
							ref="uForm"
							v-if="[2,4].includes(popupType)"
						>
							<u-form-item
								label="设备名称"
								prop="deviceName"
								borderBottom
								v-if="[2].includes(popupType)"
							>
								<u--input
									v-model="formData.deviceName"
									placeholder="请填写设备名称"
									placeholderClass="inputPlaceholder"
									border="none"
								></u--input>
							</u-form-item>
							<u-form-item
								:label="`WLAN：${wifiName}`"
								prop="wifiPassword"
								borderBottom
								v-if="[4].includes(popupType)"
							>
								<u--input
									v-model="formData.wifiPassword"
									placeholder="请填写密码"
									placeholderClass="inputPlaceholder"
									border="none"
								></u--input>
							</u-form-item>
						</u--form>
						<view class="btn-common"
							v-if="[2].includes(popupType)"
						>
							<u-button type="primary"
								text="设置网络" color="#417CE9" :disabled="!formData.deviceName"
								@click="bindSetNetwork"
							></u-button>
						</view>
						<view class="btn-common margin-top-60"
							v-if="[3,7].includes(popupType)"
						>
							<u-button type="primary"
								text="返回设置" color="#417CE9"
								@click="bindBackSet"
							></u-button>
						</view>
						<view class="btn-common"
							v-if="[4].includes(popupType)"
						>
							<u-button type="primary"
								:disabled="!formData.wifiPassword"
								text="连接" color="#417CE9"
								@click="bindLinkNetwork"
							></u-button>
						</view>
					</view>
			</view>
		</u-popup>
  </common-page>
</template>

<script>
// noinspection NpmUsedModulesInstalled
import { mapGetters } from 'vuex';
export default {
	components: {
	},
	data() {
		return {
			isRead: false,
			show: false,
			popupType: 1,
			popupContent: {
				1: {
					title: '正在接入设备...',
					subTitle: '请确保设备链接电源并在附近'
				},
				2: {
					title: '设备接入成功',
					subTitle: ''
				},
				3: {
					title: '设备接入失败',
					subTitle: ''
				},
				4: {
					title: '连接网络',
					subTitle: ''
				},
				5: {
					title: '正在连接网络...',
					subTitle: '请确保设备链接电源并在附近'
				},
				6: {
					title: '连接成功',
					subTitle: '请确保设备链接电源并在附近'
				},
				7: {
					title: '设备接入失败',
					subTitle: ''
				}
			},
			formData: {
				deviceName: '',
				wifiPassword: ''
			},
			wifiName: 'tp-link_AFEB'
		};
	},
	onLoad() {

	},
	methods: {
		// 勾选 以确认
		groupChange(ev) {
			// console.log(ev)
		},
		// 继续
		bindAddDevice() {
			if (this.isRead) {
				this.show = true;
				setTimeout(() => {
					this.popupType = 2; // 设备接入成功
					// this.popupType = 3  // 设备接入失败
				}, 1000);
				// this.openBluetoothAdapter()
			}
		},
		// 去设置网络
		bindSetNetwork() {
			// 设置设备名称
			this.$store.commit('addDevice/SET_DEVICE_PARAMAS', {
				key: 'deviceName',
				value: this.formData.deviceName
			});
			// 设置设备号
			this.$store.commit('addDevice/SET_DEVICE_PARAMAS', {
				key: 'deviceSn',
				value: ''
			});
			this.popupType = 4;
		},
		// 连接网络
		bindLinkNetwork() {
			this.popupType = 5;
			setTimeout(() => {
				this.popupType = 6; // 连接成功
				// this.popupType = 7;  // 连接失败
				setTimeout(() => { // 连接成功 去安装方式
					this.bindBackSet();
					uni.navigateTo({
						url: '/pages/device/add1'
					});
				}, 2000);
			}, 1000);
		},
		// 返回设置
		bindBackSet() {
			this.formData = {
				deviceName: '',
				wifiPassword: ''
			};
			this.wifiName = '';
			this.popupType = 1;
			this.show = false;
			this.closeBLEConnection();
			this.stopBluetoothDevicesDiscovery();
			this.closeBluetoothAdapter();
		},
		// 初始化蓝牙模块
		openBluetoothAdapter() {
			uni.openBluetoothAdapter({
				success: (res) => {
					this.startBluetoothDevicesDiscovery();
				},
				fail: (err) => {
					if (err.code === 10001) {
						uni.showToast({
							title: '当前蓝牙适配器不可用,请开启蓝牙',
							icon: 'none'
						});
					}
				}
			});
		},
		// 关闭蓝牙模块
		closeBluetoothAdapter() {
			uni.closeBluetoothAdapter({
				success: (res) => {
					console.log('蓝牙关闭成功');
				}
			});
		},
		// 开始搜寻附近的蓝牙外围设备  会有特定的 service 的 uuid 列表
		startBluetoothDevicesDiscovery() {
			uni.startBluetoothDevicesDiscovery({
				services: [],
				success: (res) => {
					this.onBluetoothDeviceFound();
				},
				fail: (err) => {
					if (err.code === 10001) {
						// 关闭蓝牙
						this.closeBluetoothAdapter();
					}
				}
			});
		},
		// 停止搜寻附近的蓝牙外围设备
		stopBluetoothDevicesDiscovery() {
			uni.stopBluetoothDevicesDiscovery({
				success: (res) => {
					console.log('停止搜寻附近的蓝牙外围设备');
				}
			});
		},
		// 监听寻找到新设备的事件
		onBluetoothDeviceFound() {
			uni.onBluetoothDeviceFound((res) => {
				const devices = res.devices;
				// this.ab2hex(devices[0].advertisData)   // 也不知道有什么作用
				// to do ...
				// 做一些判断 找到该设备 就停止搜索
				if (this.needDeviceId && this.needDeviceId === devices[0].deviceId) {
					this.stopBluetoothDevicesDiscovery(); // 停止搜索
					// 连接设备
					this.createBLEConnection();
				}
			});
		},
		// 连接设备
		createBLEConnection() {
			uni.createBLEConnection({
				deviceId: '',
				success: (res) => {
					this.popupType = 2,
					this.getBLEDeviceServices();
				},
				fail: () => {
					this.popupType = 3;
				}
			});
		},
		// 关闭连接
		closeBLEConnection() {
			// todo: 暂时设置为空字符串
			const deviceId = '';
			uni.closeBLEConnection({
			  deviceId,
			  success: (res) => {
			    console.log(res);
			  }
			});
		},
		// 获取蓝牙设备所有服务(service)。
		getBLEDeviceServices() {
			uni.getBLEDeviceServices({
			  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			  deviceId: '',
			  success: (res) => {
			    console.log('device services:', res.services);
					this.getBLEDeviceCharacteristics();
			  }
			});
		},
		// 获取蓝牙设备某个服务中所有特征值(characteristic)
		getBLEDeviceCharacteristics() {
			uni.getBLEDeviceCharacteristics({
			  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			  deviceId: '',
			  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			  serviceId: '',
			  success(res) {
			    console.log('device getBLEDeviceCharacteristics:', res.characteristics);
			  }
			});
		},
		// 设备特征值变化时的 notify 功能
		notifyBLECharacteristicValueChange() {
			uni.notifyBLECharacteristicValueChange({
			  state: true, // 启用 notify 功能
			  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			  deviceId: '',
			  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			  serviceId: '',
			  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			  characteristicId: '',
			  success: (res) => {
			    console.log('notifyBLECharacteristicValueChange success', res.errMsg);
			  }
			});
		},
		// 写入 蓝牙 写入 wifi 名 及 密码 连接 wifi
		writeBLECharacteristicValue() {
			uni.writeBLECharacteristicValue({
				deviceId: '',
				serviceId: '',
				characteristicId: '',
				value: '', // 二进制
				success: (res) => {

				},
				fail() {
					this.popupType = 3;
				}
			});
		},
		// 字符串转 二进制
		stringToBinary(str) {
		    return str.split('').map(char => {
		        return char.charCodeAt(0).toString(2).padStart(8, '0'); // 使用.padStart确保每个字符为8位
		    }).join(' ');
		},
		// 获取在蓝牙模块生效期间所有已发现的蓝牙设备
		getBluetoothDevices() {
			uni.getBluetoothDevices({
				success: (res) => {
					// 获取设备列表 to do...
				}
			});
		},
		// 获取本机蓝牙适配器状态  discovering  是否正在搜索设备  available 蓝牙适配器是否可用
		getBluetoothAdapterState() {
			uni.getBluetoothAdapterState({
				success: (res) => {
					console.log('查看本机蓝牙状态', res);
					if (!res.available) {
						uni.showToast({
							title: '蓝牙适配器不可用，是否有开启蓝牙',
							icon: 'none'
						});
						return;
					}
					if (res.discovering) {
						uni.showToast({
							title: '正在搜索设备...',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '设备已停止搜索是否需要重新开启搜索...',
							icon: 'none'
						});
						// to do ...
						// 做一些判断 或者 弹窗提示 是否重新开启搜索
						this.startBluetoothDevicesDiscovery();
					}
				}
			});
		},
		// ArrayBuffer转16进度字符串示例
		ab2hex(buffer) {
		  const hexArr = Array.prototype.map.call(
		    new Uint8Array(buffer),
		    function(bit) {
		      return ('00' + bit.toString(16)).slice(-2);
		    }
		  );
		  return hexArr.join('');
		}
	}
};
</script>

<style lang="scss" scoped>
.device-img {
	width: 488rpx;
	height: 314rpx;
	margin: 132rpx auto 0;
	display: block;
}
.txt-tip {
	color: #1E2531;
	margin-top: 176rpx;
	font-weight: bold;
	display: block;
	padding: 0 30rpx;
}
.radio-wrap {
	padding: 0 30rpx;
	margin-top: 40rpx;
}
.btn-next {
	::v-deep .u-button {
		border-radius: 60rpx;
		margin-top: 68rpx;
		&.u-button--disabled {
			background-color: #D7D7D7 !important;
			border-color: #D7D7D7 !important;
		}
		.u-button__text {
			font-size: 32rpx !important;
			font-weight: bold;
		}
	}
}
.btn-common {
	::v-deep .u-button {
		margin-top: 40rpx;
		width: 400rpx;
		&.u-button--disabled {
			background-color: #D7D7D7 !important;
			border-color: #D7D7D7 !important;
		}
	}
}
.page-box-popup {
	padding: 20rpx;
	.content-wrap {
		height: 400rpx;
		background-color: #fff;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		.title {
			font-size: 34rpx;
			font-weight: bold;
			color: #1E2531;
		}
		.subTitle {
			margin-top: 30rpx;
			font-size: 24rpx;
			color: #9FA2B4;
		}
	}
}
</style>
